<script setup>
import http from '@/http'
import { cloneDeep } from 'lodash-es'
import { useUserStore } from '../stores/user'
import { message } from 'ant-design-vue'

const formData = ref({
  username: '',
  password: ''
})

const rules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur'
    }
  ],
  password: [
    {
      required: true,
      message: '请输入密码',
      trigger: 'blur'
    }
  ]
}
const router = useRouter()
const userStore = useUserStore()
const formDataRef = ref()
const loginAction = async () => {
  await unref(formDataRef).validate()
  const pd = cloneDeep(formData.value)
  pd.password = btoa(pd.password)
  try {
    const res = await http.post('/guanplus/login', pd, {
      passAuth: true,
      noHandleError: true
    })
    userStore.setUserInfo({
      ...pd,
      token: res || ''
    })
    return router.push('/')
  } catch (e) {
    if (e?.response?.status === 401) {
      message.error('用户名或密码错误')
    }
  }
}
</script>

<template>
  <div class="h-[100vh] flex justify-center items-center">
    <a-card class="w-96" :body-style="{ paddingBottom: '10px' }">
      <template #title> 登录 </template>
      <a-form :label-col="{ span: 8 }" :model="formData" :rules="rules" ref="formDataRef">
        <a-form-item label="用户名" name="username">
          <a-input allow-clear v-model:value="formData.username" @keyup.enter="loginAction" />
        </a-form-item>
        <a-form-item label="密码" name="password">
          <a-input
            type="password"
            allow-clear
            v-model:value="formData.password"
            @keyup.enter="loginAction"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" block @click="loginAction">登录</a-button>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<style scoped lang="less"></style>
